package com.erebus.utils;

import com.erebus.feignclient.ShopCartClient;
import com.erebus.model.dto.Cart;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.taobao.base.model.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.core.NestedExceptionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

@Configuration
public class AiTools {

    private static final Logger logger = LoggerFactory.getLogger(AiTools.class);

    @Autowired
    private ShopCartClient shopCartClient;
    public record UserId(int userId) {
    }


    @JsonInclude(JsonInclude.Include.NON_NULL) // 将对象序列化为 JSON 字符串时，忽略所有值为 null 的属性
    public record ShopCart(Integer cartId, Integer userId, Integer goodsId, Integer quantity, BigDecimal unitPrice, String title, String imgUrl, Integer stockStatus, LocalDateTime createdAt, LocalDateTime updatedAt) {
    }



    @Bean
    @Description("购物车信息") // 触发关键词
    public Function<UserId, List<Cart>> getCart() {  // 第一个泛型去指定提取关键字的变量
        return request -> {
            try {
                RestResponse<List<Cart>> restResponse = shopCartClient.getCart(request.userId());
                List<Cart> cartItems = restResponse.getResult();
                return cartItems;
            }
            catch (Exception e) {
                // 记录异常日志
                logger.error("Error fetching cart for userId {}: {}",
                        request.userId(),
                        NestedExceptionUtils.getMostSpecificCause(e).getMessage());

                // 返回空列表
                return  Collections.emptyList();
            }
        };
    }



//    @Bean
//    @Description("取消机票预定")  // 触发的关键词
//    public Function<CancelBookingRequest, String> cancelBooking() {
//        return request -> {
//            flightBookingService.cancelBooking(request.bookingNumber(), request.name());
//            return "";
//        };
//        // 传统模式
////        return new Function<CancelBookingRequest, String>() {
////            @Override
////            public String apply(CancelBookingRequest request) {
////                flightBookingService.cancelBooking(request.bookingNumber(), request.name());
////                return "";
////            }
////        };
//    }

}
